package com.right.near.common.handler;

import com.alibaba.fastjson2.JSON;
import com.right.near.common.constants.SecurityConstants;
import com.right.near.common.model.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 权限处理
 *
 * @author: Star.zhu
 * @date: 2022/7/21
 */
@Slf4j
@Component
public class PermissionDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        // 登陆状态下，权限不足执行该方法
        log.warn("{}-权限不足：{}", request.getServletPath(), e.getMessage());
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        ResponseVO<String> result = new ResponseVO<>();
        result.setCode(HttpStatus.FORBIDDEN.value());
        result.setMessage(SecurityConstants.FORBIDDEN);
        String body = JSON.toJSONString(result);
        printWriter.write(body);
        printWriter.flush();
    }
}
